const Koa = require('koa');
const Router = require('koa-router')
const router = new Router();
const app = new Koa()
const static = require('koa-static');
const {
    resolve
} = require('path');
const views = require('koa-views');
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';

app.use(views('views', {
    extension: 'ejs'
}))
app.use(static(resolve(__dirname, 'static')));
 MongoClient.connect(url, { useNewUrlParser: true },(err,client)=>{
        if(err) throw err;
        client.db('jike').collection('user').find().toArray((err,res)=>{
            if(err) throw err;
            router.get('/',async ctx=>{
                    await ctx.render('index',{data:res})
            })
            client.close()
        })
})

router.get('/add', async ctx => {
    /* 增加 */
    MongoClient.connect(url, { useNewUrlParser: true },(err,client)=>{
        if(err) throw err;
        var data = [{name:"chengchao",age:18},{name:"shanshan",age:20}]
        client.db('jike').collection('user').insertMany(data,(err,res)=>{
            if(err) throw err;
            console.log('one document inserted');
            client.close()
        })
    })
})
router.get('/edit',async ctx=>{
    /* 修改 */
    MongoClient.connect(url, { useNewUrlParser: true },(err,client)=>{
        if(err) throw err;
        client.db('jike').collection('user').updateOne({"name":"jiangwei"},{
            $set:{"name":"李四"}
        },(err,res)=>{
            if(err) throw err;
        })

    })
})
router.get('/delete',async ctx=>{
    //delete?name=lisi
    MongoClient.connect(url, { useNewUrlParser: true },(err,client)=>{
        if(err) throw err;
        client.db('jike').collection('user').deleteOne({name:ctx.request.query.name},(err,res)=>{
            if(err) throw err;
            console.log('one document delete');
            client.close()
        })
    })
})
app.use(router.routes()).use(router.allowedMethods)
app.listen(8080)